(function ($) {
    $.fn.serializeFormJSON = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    var $treeTable = $('.tree-table');

    function reloadTreeTable(data) {
        $treeTable.bootstrapTable({
            data: data,
            idField: 'id',
            uniqueId: 'id',
            dataType: 'jsonp',
            toolbar: '#toolbar2',
            columns: [
                {
                    field: 'check',
                    checkbox: true
                },
                {
                    field: 'id',
                    visible: false, // false不显示
                    title: '菜单编号'
                },
                {
                    field: 'name',
                    title: '名称'
                },
                {
                    field: 'pid',
                    visible: false, // false不显示
                    title: '父级菜单编号'
                },
                {
                    field: 'type',
                    title: '菜单类型'
                },
                {
                    field: 'url',
                    title: '请求URL'
                },
                {
                    field: 'permissions',
                    title: '权限标识'
                },
                {
                    field: 'icon',
                    align: 'center',
                    title: '图标',
                    formatter: function (value, row, index) {
                        return '<span class="mdi ' + value + '" style="font-size:12px"></span>';
                    }


                },
                {
                    field: 'icon',
                    title: '图标标识',
                    formatter: function (value, row, index) {
                        return value;
                    }


                },
                {
                    field: 'sort',
                    title: '排序'
                },
                {
                    field: 'status',
                    title: '状态',
                    sortable: true,
                    /*
                     * 可以选择采用开关来处理状态显示
                     * 或者采用上个示例的处理方式
                     */
                    formatter: function (value, row, index) {
                        var is_checked = '';
                        if (value == 0) {
                            is_checked = '';
                        } else if (value == 1) {
                            is_checked = 'checked="checked"';
                        }
                        result = '<label class="lyear-switch switch-primary lyear-status"><input type="checkbox" ' + is_checked + '><span  onClick="updateStatus(' + row.id + ', ' + value + ')"></span></label>';
                        return result;
                    },
                },
                {
                    title: '操作',
                    formatter: btnGroup,  // 自定义方法
                    events: {
                        'click .edit-btn': function (event, value, row, index) {
                            editObj(row);
                        },
                        'click .del-btn': function (event, value, row, index) {
                            delObj(row);
                        }
                    }
                }
            ],
            treeShowField: 'name',
            parentIdField: 'pid',
            onResetView: function (data) {
                $treeTable.treegrid({
                    initialState: 'collapsed', // 所有节点都折叠
                    treeColumn: 1,
                    expanderExpandedClass: 'mdi mdi-folder-open',  // 可自定义图标样式
                    expanderCollapsedClass: 'mdi mdi-folder',
                    onChange: function () {
                        $treeTable.bootstrapTable('resetWidth');
                    }
                });

                // 只展开树形的第一集节点
                // $treeTable.treegrid('getRootNodes').treegrid('expand');

            },
            onCheck: function (row) {
                var datas = $treeTable.bootstrapTable('getData');

                selectChilds(datas, row, 'id', 'pid', true); // 选择子类

                selectParentChecked(datas, row, 'id', 'pid'); // 选择父类

                $treeTable.bootstrapTable('load', datas);
            },
            onUncheck: function (row) {
                var datas = $treeTable.bootstrapTable('getData');
                selectChilds(datas, row, 'id', 'pid', false);
                $treeTable.bootstrapTable('load', datas);
            },
        });
    }

    // 操作按钮组
    function btnGroup() {
        return [
            '<a type="button" class="edit-btn btn btn-xs btn-default m-r-5" title="修改" data-toggle="tooltip"><i class="mdi mdi-pencil"></i></a>',
            '<a type="button" class="del-btn btn btn-xs btn-default" title="删除" data-toggle="tooltip"><i class="mdi mdi-delete"></i></a>'
        ].join('');
    }

    /**
     * 选中父项时，同时选中子项
     * @param datas 所有的数据
     * @param row 当前数据
     * @param id id 字段名
     * @param pid 父id字段名
     */
    function selectChilds(datas, row, id, pid, checked) {
        for (var i in datas) {
            if (datas[i][pid] == row[id]) {
                datas[i].check = checked;
                selectChilds(datas, datas[i], id, pid, checked);
            }
            ;
        }
    }

    function selectParentChecked(datas, row, id, pid) {
        for (var i in datas) {
            if (datas[i][id] == row[pid]) {
                datas[i].check = true;
                selectParentChecked(datas, datas[i], id, pid);
            }
            ;
        }
    }

    function delObj(row) {
        // alert("del 方法 , id = " + id);
    }

    function editObj(currentRow) {
        var modal = $("#updateObjModal");
        modal.find('#updateObjForm [name="id"]').val(currentRow.id);
        modal.find('#updateObjForm [name="name"]').val(currentRow.name);
        modal.find('#updateObjForm [name="url"]').val(currentRow.url);
        modal.find('#updateObjForm [name="permissions"]').val(currentRow.permissions);
        modal.find('#updateObjForm [name="type"]').val(currentRow.type);
        modal.find('#updateObjForm [name="icon"]').val(currentRow.icon);
        modal.find('#updateObjForm [name="sort"]').val(currentRow.sort);
        modal.find('#updateObjForm [name="pid"]').val(currentRow.pid);

        modal.find("#updateObjForm option[value=" + currentRow.type + "]").attr("selected", true);

        $('#updateObjModal').modal('show');
    }

    function updateStatus(id, state) {
        var newstate = (state == 1) ? 0 : 1; // 发送参数值跟当前参数值相反
        $.ajax({
            type: "get",
            url: "http://www.bixiaguangnian.com/index/test/testGridJson",
            data: {id: id, state: newstate},
            dataType: 'jsonp',
            success: function (data, status) {
                if (data.code == '200') {
                    $treeTable.bootstrapTable('updateCellById', {id: id, field: 'status', value: newstate});
                } else {
                    $treeTable.bootstrapTable('updateCellById', {id: id, field: 'status', value: state}); // 因开关点击后样式是变的，失败也重置下
                }
            },
            error: function () {
                layer.msg('提交系统失败，请稍后再试', {icon: 2});
            }
        });
    }


    var page = {
        init: function () {
            var that = this;


            that.reloadTable();

            $('.table-search').click(function () {
                that.tableSearch();
            });

            $('.reset-search').click(function () {
                that.resetSearch();
            });

            $('#btn_delete').click(function () {
                that.deleteRow();
            });


            $('#addObjModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var modal = $(this);
                $("#addObjForm input").val("");
                $("#addTree").hide();
            });

            $('#addObjForm [name="type"]').change(function () {
                var selectValue = $(this).children('option:selected').val();
                // 0 一级菜单
                if (selectValue == "0") {
                    $('#addObjForm').find('input[name="pid"]').val("0");
                    $('#addObjForm').find('input[name="selectCatalog"]').val("");
                    $('#addObjForm').find('input[name="permissions"]').val("");
                    $('#addObjForm').find('input[name="selectCatalog"]').attr("disabled", "disabled");
                    $('#addObjForm').find('input[name="permissions"]').attr("disabled", "disabled");
                    $('#addObjForm').find('input[name="selectCatalog"]').attr("placeholder", "");
                    $('#addObjForm').find('input[name="permissions"]').attr("placeholder", "");
                } else {
                    $('#addObjForm').find('input[name="selectCatalog"]').removeAttr("disabled");
                    $('#addObjForm').find('input[name="permissions"]').removeAttr("disabled");
                    $('#addObjForm').find('input[name="selectCatalog"]').attr("placeholder", "请选择父级菜单");
                    $('#addObjForm').find('input[name="permissions"]').attr("placeholder", "请填写菜单对应权限标识");
                }
                // // 2 按钮
                // if(selectValue == "2"){
                //     $('#addObjForm').find('input[name="url"]').val("");
                //     $('#addObjForm').find('input[name="url"]').attr("placeholder","");
                //     $('#addObjForm').find('input[name="url"]').attr("disabled","disabled");
                // }else{
                //     $('#addObjForm').find('input[name="url"]').removeAttr("disabled");
                //     $('#addObjForm').find('input[name="url"]').attr("placeholder","请填写菜单对应URL");
                // }

            });

            $('#updateObjModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget);
                var modal = $(this);

                // $('#updateObjForm').find('select[name="type"]').attr("disabled","disabled");
                $(this).find('#updateObjForm select[name="type"]').attr("disabled", "disabled");


            });

            // $('#updateObjForm [name="type"]').change(function () {
            //     var selectValue =  $(this).children('option:selected').val();
            //     // 0 一级菜单
            //     if(selectValue == "0"){
            //         $('#updateObjForm [name="pid"]').val("");
            //         $('#updateObjForm [name="selectCatalog"]').val("");
            //         $('#updateObjForm [name="permissions"]').val("");
            //         $('#updateObjForm [name="selectCatalog"]').attr("disabled","disabled");
            //         $('#updateObjForm [name="permissions"]').attr("disabled","disabled");
            //         $('#updateObjForm [name="selectCatalog"]').attr("placeholder","");
            //         $('#updateObjForm [name="permissions"]').attr("placeholder","");
            //     }else{
            //         $('#updateObjForm [name="selectCatalog"]').removeAttr("disabled");
            //         $('#updateObjForm [name="permissions"]').removeAttr("disabled");
            //         $('#updateObjForm [name="selectCatalog"]').attr("placeholder","请选择父级菜单");
            //         $('#updateObjForm [name="permissions"]').attr("placeholder","请填写菜单对应权限标识");
            //     }
            //     // 2 按钮
            //     if(selectValue == "2"){
            //         $('#updateObjForm [name="url"]').val("");
            //         $('#updateObjForm [name="url"]').attr("placeholder","");
            //         $('#updateObjForm [name="url"]').attr("disabled","disabled");
            //     }else{
            //         $('#updateObjForm [name="url"]').removeAttr("disabled");
            //         $('#updateObjForm [name="url"]').attr("placeholder","请填写菜单对应URL");
            //     }
            //
            // });


            $('.add-obj-btn').on('click', function () {
                // var data = $('#defaultForm').serialize(); // 类似get的url拼参数方式，需要转换json
                var data = $('#addObjForm').serializeFormJSON();
                if (data.sort == null || data.sort == "") data.sort = 0;

                $.ajax({
                    type: "post",
                    url: "/menus",
                    cache: false,
                    data: JSON.stringify(data),
                    dataType: "json",
                    contentType: 'application/json;charset=utf-8',
                    success: function (data) {
                        if (data.code == "0") {
                            // 正确的其他处理...
                            layer.msg(data.msg, {icon: 6});
                            $("#tb_base").bootstrapTable('refresh');
                            $('#addObjModal').modal('hide');
                        } else {
                            // 错误的其他处理...
                            layer.msg(data.msg, {icon: 5});
                            $("#tb_base").bootstrapTable('refresh');
                        }
                    },
                    error: function (E) {
                        console.log(E);
                        layer.msg('提交系统失败，请稍后再试', {icon: 2});
                    }
                });
            });

            $('.update-obj-btn').on('click', function () {
                // var data = $('#defaultForm').serialize(); // 类似get的url拼参数方式，需要转换json
                var data = $('#updateObjForm').serializeFormJSON();
                if (data.sort == null || data.sort == "") data.sort = 0;

                $.ajax({
                    type: "put",
                    url: "/menus",
                    cache: false,
                    data: JSON.stringify(data),
                    dataType: "json",
                    contentType: 'application/json;charset=utf-8',
                    success: function (data) {
                        if (data.code == "0") {
                            // 正确的其他处理...
                            layer.msg(data.msg, {icon: 6});
                            $("#tb_base").bootstrapTable('refresh');
                            $('#updateObjModal').modal('hide');
                        } else {
                            // 错误的其他处理...
                            layer.msg(data.msg, {icon: 5});
                            $("#tb_base").bootstrapTable('refresh');
                        }
                    },
                    error: function (E) {
                        console.log(E);
                        layer.msg('提交系统失败，请稍后再试', {icon: 2});
                    }
                });
            });

            $('#btn_delete').on('click', function () {

                var selRows = $("#tree-table").bootstrapTable('getSelections');

                if (selRows.length == 0) {
                    layer.msg("请至少选择一行数据");
                    return false;
                }
                console.log(selRows);

                var postData = "";
                $.each(selRows, function (i) {
                    postData += this.id;
                    if (i < selRows.length - 1) {
                        postData += ",";
                    }
                });

                $.confirm({
                    title: '删除确认',
                    content: '请注意删除角色会同时清空角色与用户绑定关系、清空角色与菜单绑定关系，确认删除编号为[ ' + postData + ' ]的角色？！',
                    buttons: {
                        confirm: {
                            text: '确定删除',
                            btnClass: 'btn btn-danger',
                            action: function () {
                                $.ajax({
                                    type: "delete",
                                    url: "/menus/batch",
                                    cache: false,
                                    data: {'ids': postData},
                                    dataType: "json",
                                    contentType: 'application/x-www-form-urlencoded',
                                    success: function (data) {
                                        if (data.code == "0") {
                                            // 正确的其他处理...
                                            layer.msg(data.msg, {icon: 6});
                                            $("#tb_base").bootstrapTable('refresh');

                                        } else {
                                            // 错误的其他处理...
                                            layer.msg(data.msg, {icon: 5});
                                            $("#tb_base").bootstrapTable('refresh');
                                        }
                                    },
                                    error: function (E) {
                                        console.log(E);
                                        layer.msg('提交系统失败，请稍后再试', {icon: 2});
                                    }
                                });
                            }
                        },

                        cancel: {
                            text: '取消',
                            btnClass: 'btn btn-secondary',
                            action: function () {
                                // $.alert('取消!');
                            }
                        }
                        // ,
                        // somethingElse: {
                        //     text: 'Something else',
                        //     btnClass: 'btn-blue',
                        //     keys: ['enter', 'shift'],
                        //     action: function(){
                        //         $.alert('Something else?');
                        //     }
                        // }
                    }
                });


            });

            $('#btn_collapse_all').on('click', function () {
                $treeTable.treegrid('collapseAll');
                // if($treeTable.treegrid('isCollapsed')){
                //     $treeTable.treegrid('expandAll');
                //     $('#btn_collapse_all').innerHTML = '<span class="mdi mdi-folder-open" aria-hidden="true"></span>全部展开';
                // }
                // if($treeTable.treegrid('isExpanded')){
                //     $treeTable.treegrid('collapseAll');
                //     $('#btn_collapse_all').innerHTML = '<span class="mdi mdi-folder" aria-hidden="true"></span>全部关闭';
                // };
            });

            $('#btn_expand_all').on('click', function () {
                $treeTable.treegrid('expandAll');
            });

            $('#addObjForm').find('input[name="selectCatalog"]').click(function () {

                $.ajax({
                    type: "get",
                    url: "/menus/selectMenuTree",
                    cache: false,
                    data: null,
                    dataType: "json",
                    contentType: 'application/json;charset=utf-8',
                    success: function (data) {
                        if (data.code == "0") {
                            // 正确的其他处理...
                            var options = {
                                levels: 1,// 树形默认展开几级还是可展开几级了
                                showTags: true,//显示子节点数
                                data: data.tree,
                                collapseIcon: "mdi mdi-folder-open",//可收缩的节点图标
                                emptyIcon: "mdi mdi-file-outline",//设置列表树中没有子节点的节点的图标
                                expandIcon: "mdi mdi-folder-outline",  //设置列表上中有子节点的图标
                                highlightSelected: true,     //是否选中高亮显示
                                showIcon: false, // 不显示图标
                                onNodeSelected: function (event, data) {
                                    $('#addObjForm').find('input[name="selectCatalog"]').val(data.text);
                                    $('#addTree').hide();//选中树节点后隐藏树
                                    $('#addObjForm').find('input[name="pid"]').val(data.id);
                                }
                            };

                            $('#addTree').treeview(options);
                        } else {
                            // 错误的其他处理...
                            layer.msg(data.msg, {icon: 5});

                        }
                    },
                    error: function (E) {
                        console.log(E);
                        layer.msg('提交系统失败，请稍后再试', {icon: 2});
                    }
                });


            });

            $('#updateObjForm').find('input[name="selectCatalog"]').click(function () {
                $.ajax({
                    type: "get",
                    url: "/menus/selectMenuTree",
                    cache: false,
                    data: null,
                    dataType: "json",
                    contentType: 'application/json;charset=utf-8',
                    success: function (data) {
                        if (data.code == "0") {
                            // 正确的其他处理...
                            var options = {
                                levels: 1,// 树形默认展开几级还是可展开几级了
                                showTags: true,//显示子节点数
                                data: data.tree,
                                collapseIcon: "mdi mdi-folder-open",//可收缩的节点图标
                                emptyIcon: "mdi mdi-file-outline",//设置列表树中没有子节点的节点的图标
                                expandIcon: "mdi mdi-folder-outline",  //设置列表上中有子节点的图标
                                highlightSelected: true,     //是否选中高亮显示
                                showIcon: false, // 不显示图标
                                onNodeSelected: function (event, data) {
                                    $('#updateObjForm').find('input[name="selectCatalog"]').val(data.text);
                                    $('#updateTree').hide();//选中树节点后隐藏树
                                    $('#updateObjForm').find('input[name="pid"]').val(data.id);
                                }
                            };
                            $('#updateTree').treeview(options);
                        } else {
                            // 错误的其他处理...
                            layer.msg(data.msg, {icon: 5});

                        }
                    },
                    error: function (E) {
                        console.log(E);
                        layer.msg('提交系统失败，请稍后再试', {icon: 2});
                    }
                });
            });
        },
        reloadTable: function () {
            $.ajax({
                type: "get",
                url: "/menus/jsonMenuTree",
                cache: false,
                data: null,
                dataType: "json",
                contentType: 'application/x-www-form-urlencoded',
                success: function (data) {
                    if (data.code == "0") {
                        // 正确的其他处理...
                        // $("#tb_base").bootstrapTable('refresh');
                        // console.log(data.data);
                        reloadTreeTable(data.data);
                    } else {
                        // 错误的其他处理...
                        layer.msg(data.msg, {icon: 5});
                        // $("#tb_base").bootstrapTable('refresh');
                    }
                },
                error: function (E) {
                    console.log(E);
                    layer.msg('提交系统失败，请稍后再试', {icon: 2});
                }
            });
        },
        tableSearch: function () {
            $("#tb_base").bootstrapTable('refresh');
        },
        resetSearch: function () {
        },
        deleteRow: function () {
        }

    };


    page.init();

})(jQuery);